package com.dkm.ec.sale.domain;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.net.QCodec;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.dkm.base.api.service.IdGenerator;
import com.dkm.base.core.helper.SpringHelper;
import com.dkm.base.core.util.BeanUtils;
import com.dkm.biz.domain.AbstractDomain;
import com.dkm.biz.gl.domain.EavAttribute;
import com.dkm.biz.gl.domain.GlCate;
import com.dkm.biz.gl.domain.GlText;
import com.dkm.biz.gl.persistence.dao.GlCateQueryDao;
import com.dkm.biz.gl.persistence.dao.GlTextDao;
import com.dkm.biz.gl.persistence.entity.GlCatePo;
import com.dkm.biz.gl.repository.GlCateRepository;
import com.dkm.biz.gl.repository.GlTextRepository;
import com.dkm.biz.ou.persistence.entity.ShopStatPoEnum;
import com.dkm.biz.ou.service.ShopStatStatService;
import com.dkm.ec.constants.SaleStatConstants;
import com.dkm.ec.product.domain.ProdCate;
import com.dkm.ec.product.domain.ProdSeo;
import com.dkm.ec.product.domain.ProductEntity;
import com.dkm.ec.product.domain.ProductMedia;
import com.dkm.ec.product.persistence.dao.ProdSeoDao;
import com.dkm.ec.product.persistence.dao.ProductEntityDao;
import com.dkm.ec.product.persistence.dao.ProductMediaDao;
import com.dkm.ec.product.persistence.entity.ProdSeoPo;
import com.dkm.ec.product.persistence.entity.ProductEntityPo;
import com.dkm.ec.product.persistence.entity.ProductMediaPo;
import com.dkm.ec.product.repository.ProdSeoRepository;
import com.dkm.ec.product.repository.ProductEntityRepository;
import com.dkm.ec.sale.persistence.dao.SaleEntityDao;
import com.dkm.ec.sale.persistence.dao.SalePriceDao;
import com.dkm.ec.sale.persistence.dao.SaleSkuDao;
import com.dkm.ec.sale.persistence.entity.SaleEntityPo;
import com.dkm.ec.sale.persistence.entity.SaleEntityStatPo;
import com.dkm.ec.sale.persistence.entity.SaleSkuPo;
import com.dkm.ec.sale.repository.SaleEntityRepository;
import com.dkm.ec.sale.repository.SaleEntityStatRepository;
import com.dkm.ec.sale.repository.SalePackageItemRepository;
import com.dkm.ec.sale.service.SaleSkuStatService;

/**
 * 对象功能:销售产品实体 领域对象实体
 * 开发公司:SKG.COM
 * 开发人员:Yuki
 * 创建时间:2015-01-16 15:23:27
 */
@Service
@Scope("prototype")
public class SaleEntity extends AbstractDomain<String, SaleEntityPo>{
	 
	 private SaleEntityDao saleEntityDao = null;
	 @Resource
	 ProductEntityRepository productEntityRepository;
	 @Resource
	 SaleEntityRepository saleEntityRepository;
	 @Resource
	 GlTextRepository glTextRepository;
	 @Resource
	 ProdSeoRepository prodSeoRepository;
	 @Resource
	 EavAttribute eavAttribute;
	 @Resource
	 ProductMedia productMedia;
	 @Resource
	 SaleSku saleSku;
	 @Resource
	 GlCateRepository glCateRepository;
	 @Resource
	 ProdSeoDao prodSeoDao;
	 @Resource
	 SaleSkuDao saleSkuDao;
	 @Resource
	 SalePriceDao salePriceDao;
	 @Resource
	 ProductMediaDao productMediaDao;
	 @Resource
	 GlTextDao glTextDao;
	 @Resource
	 ProductEntityDao productEntityDao;
	 @Resource
	 GlCateQueryDao glCateQueryDao;
	 @Resource
	 private SaleSkuStatService saleSkuStatService;
	 @Resource
	 private ProdCate prodCate;
	 @Resource
	 private SalePackageItemRepository salePackageItemRepository;
	 @Resource
	 private IdGenerator idGenerator;
	 @Resource
	 private SaleEntityStatRepository saleEntityStatRepository;
	 @Resource
	 private ShopStatStatService shopStatStatService;
	 
	 
	private static Logger logger = LoggerFactory.getLogger(SaleEntity.class);

	protected void init(){
		saleEntityDao = SpringHelper.getBean(SaleEntityDao.class);
		setDao(saleEntityDao);
	}	 
	 
	/**
	 * 保存【产品】
	 * @param userId 
	 * @param 
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public void saveSaleEntity(String userId) throws ParseException {
		boolean isNew = StringUtils.isEmpty(getData().getSaleId())?true:false;
		ProductEntity productEntity = new ProductEntity();
		ProductEntityPo  productEntityPo = null;
		if(!isNew){
			 productEntity = productEntityRepository.load(getData().getSaleId());
		}else{
			 productEntity = productEntityRepository.newInstance();	
		}
		productEntityPo = productEntity.getData();
	    //保存详细内容		
		String descContent=getData().getDescContent();
	/*	String descContent1=getData().getDescContent1();
		String descContent2=getData().getDescContent2();
		String descContent3=getData().getDescContent3();*/
		if(StringUtils.isNotEmpty(getData().getDescFid())){
			GlText glText = glTextRepository.load(getData().getDescFid());
			 glText.saveText(descContent);
		}else{
			GlText glText = glTextRepository.newInstance();
			String descFid=glText.saveText(descContent);
			getData().setDescFid(descFid);
		}	
		
	/*	if(StringUtils.isNotEmpty(getData().getAfterService())){
			GlText glText = glTextRepository.load(getData().getAfterService());
			 glText.saveText(descContent1);
		}else{
			GlText glText = glTextRepository.newInstance();
			String descFid=glText.saveText(descContent1);
			getData().setAfterService(descFid);
		}	
		
		if(StringUtils.isNotEmpty(getData().getRealPhotos())){
			GlText glText = glTextRepository.load(getData().getRealPhotos());
			 glText.saveText(descContent2);
		}else{
			GlText glText = glTextRepository.newInstance();
			String descFid=glText.saveText(descContent2);
			getData().setRealPhotos(descFid);
		}	
		
		if(StringUtils.isNotEmpty(getData().getQualityReport())){
			GlText glText = glTextRepository.load(getData().getQualityReport());
			 glText.saveText(descContent3);
		}else{
			GlText glText = glTextRepository.newInstance();
			String descFid=glText.saveText(descContent3);
			getData().setQualityReport(descFid);
		}	*/
		
		//保存产品
		try {
			BeanUtils.copyProperties(productEntityPo, getData());	
			GlCate subGlCate = glCateRepository.load(productEntityPo.getSubCateId());
			if(subGlCate != null){
				GlCatePo glCatePo = subGlCate.getData();
				productEntityPo.setMainCateId(glCatePo.getParentId());
			}
			if(!isNew){
				productEntityPo.setId(getData().getSaleId() );
				ProductEntityPo productEntityPoDB = productEntityRepository.load(productEntityPo.getId()).getData();
				if(productEntityPoDB!=null) {
					if(!productEntityPoDB.getMainCateId().equals(getData().getMainCateId())){
						//更新分类的产品数量
						GlCate glCate = glCateRepository.newInstance();
						glCate.updateStatWithParent(productEntityPoDB.getMainCateId(),-1);
						
						glCate = glCateRepository.newInstance();
						glCate.updateStatWithParent(getData().getMainCateId(),1);		
					}
				}
			}else{
				GlCate  glCate = glCateRepository.newInstance();
				glCate.updateStatWithParent(getData().getMainCateId(),1);	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
		productEntityPo.setKey(idGenerator.genSid());
		productEntityPo.setShopId(userId);
		productEntity.setData(productEntityPo);
		productEntity.save();	
		if(isNew){
			getData().setSaleId(productEntity.getId());
			getData().setId(productEntity.getId());
			setNewFlag(true);			
			shopStatStatService.addShopStat(userId,ShopStatPoEnum.product_qty_,1);
		}else{
			
		}
		//保存属性值
		eavAttribute.saveAttrValue(getData().getAttrDataMap(),productEntity.getId(),getData().getEavSetKey());
		
		//保存seo
		/*ProdSeoPo prodSeoPo = getData().getProdSeoPo();
		if(prodSeoPo!=null && StringUtils.isNotEmpty(prodSeoPo.getId())){
			prodSeoDao.update(prodSeoPo);
		}else{
			ProdSeo prodSeo = prodSeoRepository.load(productEntity.getId());
			if(prodSeo!=null&&prodSeo.getData()!=null){
				try {
					prodSeoPo.setId(prodSeo.getData().getId());
					} catch (Exception e) {
					e.printStackTrace();
				}					
				prodSeoDao.update(prodSeoPo);
			}else{
				if(prodSeoPo==null)prodSeoPo = new ProdSeoPo();
				prodSeoPo.setId(productEntity.getId());
				prodSeoDao.create(prodSeoPo);
			}
		}	*/
		//保存效果图
		productMedia.saveMedias(getData().getProductMediaPos(), productEntity.getId(),"product");
	//	productMedia.saveMedias(getData().getProductMediaColorPos(), productEntity.getId(),"color");
		//getData().setSaleMediaId(homeMediaId);
		super.save();//保存saleEntityPo对象
		
		//保存类型prodType
		if(getData().getProdCatePos()!=null && getData().getProdCatePos().size()>0){
			 prodCate.saveProdCateWithProdId(getData().getProdCatePos(), productEntity.getId());
		}
		
		//保存SKU
		//如果是产品包则不保存|更新 sku和价格
		if(!getData().getSeType().equals("package")){
			saleSku.saveSaleSkusWithSalePrice(getData().getSaleSkuPos(),productEntity.getId());
		}else {
			for(SaleSkuPo saleSkuPoDB :getData().getSaleSkuPos()){
				//SkuSolr.delete(saleSkuPoDB);//删除solr信息
			//	SolrSaleUtils.newInstance().delete(saleSkuPoDB.getId()); 
			}
		}
		if(getData().isNeedGenSolr()){
				//solr AddOrUpdate
				if(isNew){
//					SkuSolr.add(getSaleEntityPo(productEntity));
				}else{
//					SkuSolr.update(getSaleEntityPo(productEntity));
				}
			}
	}
	
	/**
	 * 删除【家居产品】
	 * @param id
	 * @param homeType
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public void destoryEntity(String id){
				//delete attr
				eavAttribute.deleteAttrValueByEntityId(id);
				//delete seo
				prodSeoDao.delete(id);
				//delete Product Media
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("prodId", id);
				productMediaDao.deleteByKey("deleteByProdId", params);
				//delete sku SKG_SALE_PRICE【产品销售价格】
				salePriceDao.deleteByKey("deleteByProdId", params);
				//delete sku
				saleSkuDao.deleteByKey("deleteByProdId", params);
				
				//delete desc
				SaleEntity saleEntity = saleEntityRepository.load(id);
				if(saleEntity!=null&&saleEntity.getData()!=null&&saleEntity.getData().getDescFid()!=null){
					glTextDao.delete(saleEntity.getData().getDescFid());
				}
				//delete saleEntity
				super.destroy(id);
				//delete product
				productEntityDao.delete(id);
			
				//solr delete
//				SkuSolr.deleteBySaleId(id);
		//		SolrSaleUtils.newInstance().delete(id);
				
				//修改glcate的统计数量
				//更新分类的产品数量
				GlCate glCate = glCateRepository.newInstance();
				glCate.updateStatWithParent(getData().getMainCateId(),-1);
				
	}		
	/**
	 * 加载详细信息
	 * @param
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
public void loadForDetail(){
		
        //查询详细内容		
		if(StringUtils.isNotEmpty(getData().getDescFid())){
			GlText glText = glTextRepository.load(getData().getDescFid());
			if(glText!=null){
				getData().setDescContent(glText.getData().getText());	
			}
		}
		if(StringUtils.isNotEmpty(getData().getMainCateId())){
			GlCatePo glCatePo = glCateQueryDao.get(getData().getMainCateId());
			getData().setCateName(glCatePo.getName());
			getData().setCateKey(glCatePo.getKey());
		}
		
		  //查询EntitySeo		
		if(StringUtils.isNotEmpty(getData().getId())){
			ProdSeo prodSeo = prodSeoRepository.load(getData().getId());
			if(prodSeo!=null){
				getData().setProdSeoPo(prodSeo.getData());		
			}
		
		}
	}


/**
 * 加载价格表
 * @param
 * @return
 * @throws Exception 
 * @exception 
 * @since  1.0.0
 */
public void loadSaleSku(){
	
}

}

